#coding:utf-8
#user

import urllib
import base64

from flask import Blueprint, request, jsonify
from flask_restful import Resource, Api
from flask import make_response

from module.spider import config
from module.spider import webspider

webSpiderRoute = Blueprint('webSpiderRoute', __name__)
api = Api(webSpiderRoute)

class WebSpiderConfigs(Resource):
    def get(self):
        return config.listConfig()

    def post(self):
        data = request.get_json()
        config.addConfig(data)
        return data['name']

class WebSpiderConfig(Resource):
    def get(self,id):
        return config.getConfig(id)

    def delete(self,id):
        config.deleteConfig(id)
        return id

    def put(self, id):
        # 修改单条数据
        data = request.get_json()

        config.updateConfig(id, data)
        return id

class ScriptWebSpiders(Resource):
    def post(self):
        data = request.get_json()
        webspider.start(data)
        return data['save-folder']

class ScriptWebSpider(Resource):
    def get(self,saveFolder):
        saveFolder = str(base64.b64decode(saveFolder), "utf-8")
        saveFolder = urllib.parse.unquote(saveFolder)
        zipbyte = webspider.getSpiderDownloadData(saveFolder)

        resp = make_response(zipbyte) # 响应体数据
        resp.status = 200 # 状态码

        resp.headers['Content-Type'] = 'application/octet-stream' # 通过字典的形式添加响应头
        resp.headers['Content-disposition'] = 'attachment; filename=' + '爬虫执行结果.zip'.encode("utf-8").decode("latin1")

        return resp

class SpiderRuning(Resource):
    def get(self,saveFolder):
        saveFolder = str(base64.b64decode(saveFolder), "utf-8")
        saveFolder = urllib.parse.unquote(saveFolder)
        result = webspider.isSpiderRuning(saveFolder)
        return result

api.add_resource(WebSpiderConfigs, '/web-spider-configs/')
api.add_resource(WebSpiderConfig, '/web-spider-configs/<int:id>/')

api.add_resource(ScriptWebSpiders, '/script-web-spiders/')
api.add_resource(ScriptWebSpider, '/script-web-spiders/<string:saveFolder>/')

api.add_resource(SpiderRuning, '/spider-runings/<string:saveFolder>/')